<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品数据汇总工具</title>
    <!-- 引入表格转图片库 -->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }
        body {
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .paste-area {
            width: 100%;
            height: 150px;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            resize: none;
            font-size: 14px;
            line-height: 1.5;
        }
        .tip {
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
        }
        .summary-btn {
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        .summary-btn:hover {
            background-color: #45a049;
        }
        .result-area {
            display: none;
            margin-top: 20px;
        }
        .table-container {
            overflow-x: auto;
            margin-bottom: 15px;
        }
        .product-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        .product-table th, .product-table td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .product-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .total-row {
            background-color: #fff8e1;
            font-weight: bold;
        }
        .save-img-btn {
            padding: 10px 20px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
        }
        .save-img-btn:hover {
            background-color: #0b7dda;
        }
        .error-tip {
            color: #f44336;
            font-size: 12px;
            margin-bottom: 15px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 数据粘贴区 -->
        <textarea class="paste-area" placeholder="请粘贴商品数据，格式：每行一个商品，产品名 单价（空格分隔）
示例：
云朵蛋糕 19.9
小吐司 19.9
坚果乳 38.9"></textarea>
        <div class="tip">提示：每行1个商品，产品名与单价用空格分隔，如“水果萝卜 9.9”</div>
        <div class="error-tip" id="errorTip">格式错误！请按“产品名 单价”格式粘贴，每行1个商品</div>
        
        <!-- 汇总按钮 -->
        <button class="summary-btn" id="summaryBtn">汇总数据</button>
        
        <!-- 结果显示区（默认隐藏） -->
        <div class="result-area" id="resultArea">
            <div class="table-container" id="tableContainer">
                <table class="product-table" id="productTable">
                    <thead>
                        <tr>
                            <th>产品</th>
                            <th>单价（¥）</th>
                            <th>数量</th>
                            <th>小计（¥）</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 汇总数据将动态插入 -->
                    </tbody>
                    <tfoot>
                        <tr class="total-row">
                            <td colspan="3">合计金额</td>
                            <td id="totalAmount">¥0.00</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <!-- 保存表格图片按钮 -->
            <button class="save-img-btn" id="saveImgBtn">保存表格图片</button>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const pasteArea = document.querySelector('.paste-area');
        const summaryBtn = document.getElementById('summaryBtn');
        const resultArea = document.getElementById('resultArea');
        const tableBody = document.getElementById('tableBody');
        const totalAmount = document.getElementById('totalAmount');
        const saveImgBtn = document.getElementById('saveImgBtn');
        const errorTip = document.getElementById('errorTip');
        const tableContainer = document.getElementById('tableContainer');

        // 初始化：文本区为空（已移除默认数据）
        
        // 汇总数据逻辑
        summaryBtn.addEventListener('click', () => {
            const pasteText = pasteArea.value.trim();
            if (!pasteText) {
                errorTip.textContent = "请先粘贴商品数据！";
                errorTip.style.display = 'block';
                resultArea.style.display = 'none';
                return;
            }

            // 解析粘贴数据（按行分割，提取产品和单价）
            const lines = pasteText.split('\n');
            const productList = [];
            let formatError = false;

            lines.forEach(line => {
                const lineTrim = line.trim();
                if (!lineTrim) return; // 跳过空行
                // 按空格分割（支持产品名含1个空格，如“水果玉米”）
                const parts = lineTrim.split(/\s+/);
                if (parts.length < 2) {
                    formatError = true;
                    return;
                }
                // 提取产品名（前n-1个部分）和单价（最后1个部分）
                const productName = parts.slice(0, -1).join(' ');
                const price = parseFloat(parts[parts.length - 1]);
                if (isNaN(price) || price < 0) {
                    formatError = true;
                    return;
                }
                productList.push({
                    name: productName,
                    price: price,
                    quantity: 1, // 默认数量1
                    subtotal: price * 1
                });
            });

            // 格式错误处理
            if (formatError) {
                errorTip.textContent = "格式错误！请按“产品名 单价”格式粘贴，每行1个商品（单价为数字）";
                errorTip.style.display = 'block';
                resultArea.style.display = 'none';
                return;
            }
            errorTip.style.display = 'none';

            // 按产品分组，计算总数量和总小计
            const productGroup = {};
            productList.forEach(product => {
                if (productGroup[product.name]) {
                    productGroup[product.name].quantity += product.quantity;
                    productGroup[product.name].subtotal += product.subtotal;
                } else {
                    productGroup[product.name] = { ...product };
                }
            });

            // 生成表格内容
            tableBody.innerHTML = '';
            let total = 0;
            Object.values(productGroup).forEach(product => {
                total += product.subtotal;
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${product.name}</td>
                    <td>${product.price.toFixed(2)}</td>
                    <td>${product.quantity}</td>
                    <td>${product.subtotal.toFixed(2)}</td>
                `;
                tableBody.appendChild(tr);
            });

            // 显示合计金额
            totalAmount.textContent = `¥${total.toFixed(2)}`;

            // 显示结果区
            resultArea.style.display = 'block';
        });

        // 保存表格图片逻辑（使用html2canvas）
        saveImgBtn.addEventListener('click', () => {
            // 等待表格渲染完成，延迟执行
            setTimeout(() => {
                html2canvas(tableContainer, {
                    scale: 2, // 提高图片清晰度（2倍缩放）
                    useCORS: true,
                    logging: false
                }).then(canvas => {
                    // 转为图片链接
                    const imgData = canvas.toDataURL('image/png');
                    // 创建下载链接
                    const link = document.createElement('a');
                    link.download = `商品汇总表格_${new Date().getTime()}.png`;
                    link.href = imgData;
                    link.click();
                }).catch(err => {
                    alert('保存图片失败，请重试！');
                    console.error(err);
                });
            }, 300);
        });
    </script>
</body>
</html>
    